<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <style>
    
  </style>
</head>
<body>
  用户名：<input type="text" class="username"><br>
  密码：<input type="text" class="password"><br>
  <input type="button" value="登录" class="login">
  <br>
  <br>
  <table border="1" width="750">
    <thead>
      <tr>
        <th>手机号</th>
        <th>姓名</th>
        <th>用户名</th>
        <th>部门</th>
        <th>权限</th>
      </tr>
    </thead>
    <tbody>
    </tbody>
  </table>
</body>
<script src="./ajax.js"></script>
<script>

  class TestAjax{
    constructor(){
      this.un = document.querySelector(".username");
      this.pw = document.querySelector(".password");
      this.login = document.querySelector(".login");
      this.tbody = document.querySelector("tbody");
      this.loginUrl = "http://10.11.55.249:3000/login";
      this.getUserUrl = "http://10.11.55.249:3000/getuser";

      // 2. 初始立即读取本地存储中的登录框成功标志
      this.token = localStorage.getItem("token");

      // 3. 获取用户信息（会使用到登录成功标志）
      this.getUserLoad();

      this.addEvent();
    }
    addEvent(){
      const that = this;
      this.login.onclick = function(){
        that.loginLoad();
      }
    }
    loginLoad(){
      ajax({
        url: this.loginUrl,
        data:{
          username: this.un.value,
          password: this.pw.value
        },
        success:res=>{
          res = JSON.parse(res);
          if(res.code === 0){
            this.token = res.data.token;
            // 1. 登录成功后，将成功的标志存入本地存储
            localStorage.setItem("token", this.token );
            this.getUserLoad();
          }else{
            alert(res.msg);
          }
        }
      })
    }
    getUserLoad(){
      ajax({
        url: this.getUserUrl,
        data:{
          token: this.token
        },
        success:res=>{
          res = JSON.parse(res);
          // 4. 请求成功后，根据后端响应数据，判断是否获取用户信息成功
          if(res.code === 0){
            // 5. 未成功
            alert("登录失效，请重新登录");
            this.tbody.innerHTML = "";
          }else if(res.code === 1){
            // 6. 成功
            this.userMsg = res.data;
            this.render()
          }
        }
      })
    }
    render(){
      let str = "";
      this.userMsg.forEach(val=>{
        str += `<tr>
                  <td>${val.tel}</td>
                  <td>${val.uName}</td>
                  <td>${val.username}</td>
                  <td>${val.tId ? val.tId : "无"}</td>
                  <td>${val.power}</td>
                </tr>`;
      })
      this.tbody.innerHTML = str;
    }
  }

  new TestAjax;

</script>
</html>